<?php
namespace app\index\controller;
use think\Db;
use think\Controller;
use app\common\controller\PaylogBaseController;
use app\common\model\Shopping;
use app\common\model\CorePayLog;


class Pay extends Controller
{
	protected function _initialize() {
		$type=get_brower_type();
		$this->assign('browder_type',$type);
		if(!empty(input('order_sn'))){
			$uid = db('log_paylog')->where('order_sn',input('order_sn'))->value('uid');
			$user_info = db('info_user')->where('id',$uid)->find();
			session('info_user',$user_info);
		}
		
		$type=get_brower_type();//判断是微信还是支付宝打开
		if($type==2){//微信
			session('type_wxpay',2);
		}else{
			session('type_wxpay',1);
		}
	}
	public function index()
    {
       return  $this->fetch();
    }
	
	//购买成功
	function change_success(){
		
		if(request()->isPost()){
			$longitude = input('longitude');
			$latitude = input('latitude');
	    	
	    	//获取订单信息
	    	$cpay_log = db('log_paylog')
	    				->where('order_sn',input('order_sn'))
	    				->where('state',2)
	    				->find();
	    				
	    	if($cpay_log['order_type'] == 9){
	    		//获取oem信息
	    		$oem_info = db('info_oem')->where('id',$cpay_log['uid'])->find();
	    		if($oem_info['user_level'] == 1){
	    			$agent_where['oem_id'] = $oem_info['id'];
	    		}elseif($oem_info['user_level'] == 2){
	    			$agent_where['agency_id1'] = $oem_info['id'];
	    		}else{
	    			$agent_where['agency_id2'] = $oem_info['id'];
	    		}
	    		//获取收款商家信息
	    		$agent_info = db('info_agent')->where($agent_where)->find();
	    	}else{
	    		//获取收款商家信息
	    		$agent_info = db('info_agent')->where('id',$cpay_log['agent_id'])->find();
	    	}
	    	if(config('open_sq') == 1){
	    		//检查商家是否加入联盟
		    	$where['b.state'] = 2;
		    	$where['b.is_state'] = 1;
		    	$where['a.agent_id'] = $agent_info['id'];
		    	 
		    	$list = db('union_member')
						->alias('a')
						->join('union_agent b','a.union_id = b.id')
						->where($where)
						->order('b.add_time desc')
						->select();
		    	if(count($list)>0){
		    		
		    		$sql ='select *,ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli'.
									' from union_member  where agent_id = '.$agent_info['id'].' order by juli limit 1 ';
		    		$union_info = Db::query($sql); 
		    		
		    		//获所有商家id 
		    		$id_list = Db::table('union_member')->field('agent_id')->where('union_id',$union_info[0]['union_id'])->select();
		    		$id_string ="";
		    		foreach ($id_list as $key=>$value){
		    			$id_string .= $value['agent_id'].",";
		    		}
		    		 $id_string = substr($id_string, 0,strlen($id_string)-1);
		    		$sql ="select id,agent_name,address,logo,ad_score,is_score,".
									"ROUND(6378.138*2*ASIN(SQRT(POW(SIN((".$latitude."*PI()/180-latitude*PI()/180)/2),2)+COS(".$latitude."*PI()/180)*COS(latitude*PI()/180)*POW(SIN((".$longitude."*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli".
									" from info_agent where id > 1 and is_huilu =1 and status =1  and ad_money>0.2 and id in (".$id_string.")  order by juli limit 5 ";
		    	}else{
					$sql ='select id,agent_name,address,logo,ad_score,is_score,'.
									'ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli'.
									' from info_agent where id > 1 and is_huilu =1 and status =1  and ad_money>0.2  order by juli limit 5 ';
		    	}
			}else{
				$sql ='select id,agent_name,address,logo,ad_score,is_score,'.
									'ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli'.
									' from info_agent where id > 1  and is_huilu =1 and status =1  order by juli limit 5 ';
			}
			
	    	$agent_list = Db::query($sql);
	    	$this->assign('agent_list',$agent_list);
	    	$this->assign('cpay_log',$cpay_log);
	    }
	    $this->get_unionid();
       	return  $this->fetch('pay_success2');
	}
	 //授权获取unionid
	public function get_unionid(){
		$user=session('info_user');
		$type=get_brower_type();//判断是微信还是支付宝打开
        $redirect='https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        if($user&&$type==2&&!$user['unionid']) {
			$auth_code=input("code");
            $url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect';
          
            if(!$auth_code){
                Header("Location: $url");
                exit;
            }else{
				$union_info=union_id($auth_code);
				$openid=$union_info['openid'];
				$data['nickname']=$union_info['nick_name'];
				$data['logo']=$union_info['headimgurl'];
				$data['unionid']=$union_info['unionid'];
				$data['openid']=$openid;
				$res=db("info_user")->where('id',$user['id'])->update($data);
				if($res){
					$user_info = db('info_user')->where('id',$user['id'])->find();
					session('info_user',$user_info);
				}
            }
       	}
	}

	//鼓励金付款成功
    public function pay_success()
    {
    	if(request()->isPost()){
    		$type=get_brower_type();
	    	$longitude = input('longitude');
			$latitude = input('latitude');
	    	//获取订单信息
	    	$cpay_log = db('log_paylog')
	    				->where('order_sn',input('order_sn'))
						->find();

					
		
	    	//获取收款商家信息
			$agent_info = db('info_agent')->where('id',$cpay_log['agent_id'])->find();
			
	    	//获取付款用户积分余额
	    	$user_score = db('info_user')->field('score,is_atten')->where('id',$cpay_log['uid'])->find();
	    	
		   $sql ='select id,agent_name,address,logo,ad_score,is_score '.
									' from info_agent where id > 1 and is_huilu =1 and oem_id = '.config("cut_oem_id").' and status =1  limit 5 ';

	    	$agent_list = Db::query($sql);
			
			if($cpay_log['balance']!=$cpay_log['origin_price']){
	    		if($cpay_log['member_score']>0){
				$cpay_log['balance']=$cpay_log['balance']+$cpay_log['np_price'];
				}
		    	if($cpay_log['np_price']==$cpay_log['origin_price']){
		    		$cpay_log['balance']=$cpay_log['origin_price'];
		    	}
	    	}
	    	$pay_info['agent_list'] = $agent_list;
	    	$pay_info['pay_log_info'] = $cpay_log;
	    	$pay_info['user_core'] = $user_score;
			$pay_info['type'] = $type;
	    	return json(['code'=>200,'pay_info'=>$pay_info]);
		}
		
		$this->get_unionid(); 

		// if(input('order_sn')){
		// 	$date['pay_time']=now_time();
		// 	$date['is_payment']=2;
		// 	$order_api = db('pay_order_api')->where('sb_no',input('order_sn'))->update($date);
		// 	if($order_api){
		// 		header("Content-Type: text/plain_;charset=utf-8");
		// 		$model =  model('Shopping');
		// 		$data=['status'=>'S','order_number'=>session('order_number'),'money'=>session('amount')];
		// 		$str=$model->setSign($data);
		// 		$code_url=$model->arrToUrl($data);
		// 		$notify_url=session('is_notify_url').'?'.$code_url.'&sign='.$str;
		// 		for($i=1; $i<=3; $i++){
		// 			if(Header("Location: $notify_url")=="success"){
		// 				break;
		// 			}else{
		// 				continue;
		// 			}
		// 		}
		// 		exit;
		// 	}	
		// }	

       	return  $this->fetch();
    }

    
    //鼓励金购买
    public function recharge()
    {
    	$type=get_brower_type();//判断是微信还是支付宝打开
    	//获取用户类型，1：oem,2:商家
    	$user_type = input('user_type');
    	//获取购买类型；1：购买积分；2购买鼓励金
    	$change_type = input('change_type');
    	
    	if(!input('user_id') || input('user_id')<0 || !$user_type || $user_type <0 || !$change_type || $change_type<0){
    		echo "数据异常";exit;	
    	}
    	$redirect='http://'.$_SERVER['HTTP_HOST'].'/index/pay/recharge?user_id='.input('user_id').'&change_type='.input('change_type').'&user_type='.input('user_type');
    	if($type==1){
			$auth_code=input("auth_code");
			$url ='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.config('alipay_appid').'&scope=auth_base&redirect_uri='.urlencode($redirect);
		}else{
			$auth_code=input("code");
			$url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect';
		}
		if(!$auth_code){
			Header("Location: $url");
			exit;
		}else{
			if($type==1){//支付宝openid
				$pay_type = 3;
				$field="alipay_id";
				$openid=user_ali_id($auth_code);
				
			}elseif($type==2){//微信openid
				$pay_type = 2;
				$field="openid";
				if(session('cut_auth_code') != $auth_code && session('prior_auth_code') != $auth_code){
					session('prior_auth_code',session('cut_auth_code'));
					session('cut_auth_code',$auth_code);
					$union_info=union_id($auth_code);
					$openid=$union_info['openid'];
					$data['nickname']=$union_info['nick_name'];
					$data['logo']=$union_info['headimgurl'];
					$data['unionid']=$union_info['unionid'];
					$data['openid']=$openid;
				}else{
					Header("Location: $url");
					exit;
				}
			}
			//判断购买用户类型
			if($user_type == 1){
				$data_info = db('info_oem')->where('id',input('user_id'))->find();
				//检查oem是否存在
				if(!$data_info){
		    		echo "访问异常，oem不存在";exit;	
		    	}
				$user_id=0;
			}else{
				$data_info = db('info_agent')->where('id',input('user_id'))->find();
				//检查商家是否存在
				if(!$data_info){
		    		echo "访问异常，商家不存在";exit;	
		    	}
				//检查openid
				if($openid){
					$user=db('info_user')->where($field,$openid)->find();
					if(!$user){
						if($type==2&&isset($data)){
	            		 $user_info = db('info_user')->where("unionid",$data['unionid'])->find();
						 if($user_info){
						 	$res=db("info_user")->where('id',$user_info['id'])->update($data);
					 	 	$user_id=$user_info['id'];
						 }
	            		}
						if(!isset($user_id)||!$user_id){
							$data[$field]=$openid;
							$data['level']			= $data_info['user_id'];
							$data['oem_id']			= $data_info['oem_id'];
							$data['agency_id']		= $data_info['agency_id'];
							$data['agency_id1']		= $data_info['agency_id1'];
							$data['agency_id2']		= $data_info['agency_id2'];
							$data['tj_agent']		= $data_info['id'];
							$data['add_time']		= now_time();
							$data['reg_type']		= 4;  //鼓励金购买
							$data['member_level']	= "ratio_one";
							$user_id=Db::name('info_user')->insertGetId($data);
						}
					}else{
						if(!$user['unionid']&&$type==2&&isset($data)){
	            			$res=db("info_user")->where('id',$user['id'])->update($data);
		            	}
						$user_id=$user['id'];
					}
					$user=db("info_user")->where("id",$user_id)->find();
					session("info_user",$user);
					//新用户领取奖励金
					if($type==2){
						receive();
					}
				}
			}
		}
    	
    	$pay_info['recharge_user_id']	=	$user_id;		//付款用户
    	$pay_info['get_recharge_user_id']	=	input('user_id');	//获得鼓励金用户
    	$pay_info['get_recharge_user_type']	=	$user_type;			//获得鼓励金用户类型1：oem;2:商家
    	$pay_info['pay_type']	=	$pay_type;						//购买方式2：微信;3：支付宝
    	session('recharge_pay_info',$pay_info);
    	
    	$this->assign('data_info',$data_info);
    	if($type==1){
    		return  $this->fetch("ng");
    	}else{
    		return  $this->fetch();
    	}
       
    }
    
    
    function score_pay(){
    	if(request()->isPost()){
			$pay_info = session('recharge_pay_info');
			if($pay_info){
				//订单编号
				$order_sn = order_create_no();
				//检查购买用户类型
				if($pay_info['get_recharge_user_type'] == 1){	//oem 购买
					//获取oem信息
					$oem_info = db('info_oem')->where('id',$pay_info['get_recharge_user_id'])->find();
					$result = $this->recharge_log($oem_info['id'],$oem_info['id'],input('pay_money'),9,$order_sn,$pay_info['pay_type'],'购买鼓励金',$oem_info['id']);
				}else{	//商家购买
					$agent_info = db('info_agent')->where('id',$pay_info['get_recharge_user_id'])->find();
					$user_info  = db('info_user')->where('id',$pay_info['recharge_user_id'])->find();
					if(input('charge_type')==1){	//积分购买
						//打印支付日志
						$result = $this->recharge_log($user_info['id'],$agent_info['id'],input('pay_money'),5,$order_sn,$pay_info['pay_type'],'用户'.$user_info['mobile'].'为商家'.$agent_info['cb_login_name'].'购买鼓励金',$agent_info['oem_id']);
					}else{ //广告购买
						//打印支付日志
						$result = $this->recharge_log($user_info['id'],$agent_info['id'],input('pay_money'),4,$order_sn,$pay_info['pay_type'],'用户'.$user_info['mobile'].'为商家'.$agent_info['cb_login_name'].'购买广告费',$agent_info['oem_id']);
					}
				}
				if($result){
					$redirect_url = 'http://'.$_SERVER['HTTP_HOST'].'/index/pay/change_success?order_sn='.$order_sn;
					//发起支付
					if($pay_info['pay_type']==3){//支付宝
							$url=pay_code('H48007350000003','e1a870150cbccb203a3ed5841e84123d','2f9b3217d30f06966e69edeb53b74b8d',input('pay_money'),1,$order_sn,'',$redirect_url);
					}elseif($pay_info['pay_type']==2) {//微信扫码
							$url=pay_code('H48007350000003','e1a870150cbccb203a3ed5841e84123d','2f9b3217d30f06966e69edeb53b74b8d',input('pay_money'),2,$order_sn,'',$redirect_url);
					}
					return json(["code"=>200,"url"=>$url]);
				}
				
			}
    	}
    }
    
    function pay_test(){
    	$paylog = new PaylogBaseController();
		$paylog->print_log(input('order_sn'),1);
    }
    
    //计算付款金额
    function check_money(){
    	if(request()->isPost()){
			$origin_price = $_POST['origin_price'];	//应付金额
			$np_price=0;//不参与抵扣的金额
			if($_POST['np_price']){
				$np_price=$_POST['np_price'];
			}
			$glj_price=$origin_price-$np_price;//鼓励金抵扣的金额
			$pay_price = $glj_price;				//实付金额	
			$agent_info = db('info_agent')->where('id',$_POST['agent_id'])->find();
			$user_info  = db('info_user')->where('id',$_POST['user_id'])->find();
			//是否开启积分营销
			if($agent_info['is_score'] == 1&&($origin_price!=$np_price)){
				//计算当前需付积分
				$need_score = bcmul($agent_info['ad_score']/100, $glj_price, 4);
				//计算赠送积分
				$give_score = bcmul($agent_info['zs_score']/100, $glj_price, 4);
				//检查用户积分实付充足
				if($user_info['score']>0){	//抵扣积分
					
					if(bccomp($user_info['score'], $need_score, 4)>=0){
						//检查商家是否开启积分抵扣
						if($agent_info['ad_score']>0 && bccomp($glj_price,0.1, 2)>=0){
							//计算实付金额
							$pay_price = bcsub($glj_price, $need_score, 2);
							$pay_price=$pay_price+$np_price;
						}
					}else{
						//检查商家是否开启积分抵扣
						if($agent_info['ad_score']>0 && bccomp($glj_price, 0.1, 2)>=0){
							//计算实付金额
							$pay_price = bcsub($glj_price, $user_info['score'], 2);
							$pay_price=$pay_price+$np_price;
						}
					}
					
				}else{//积分赠送
					$pay_price=$origin_price;
					//检查商家积分是否充足
					if(bccomp($agent_info['score'],$give_score,4)<0){
						//关闭商家积分营销
						db("info_agent")->where('id', $agent_info['id'])->update(['is_score' =>2]);
						
						$tem_w['title']='商家积分不足';
						$tem=db("sms_template")->where($tem_w)->find();
						$msg=sendsms($tem['sign_name'],$agent_info['mobile'],$tem['tid'],'code','');
						
						return json(["code"=>400,'msg'=>'商家积分不足，无法赠送积分']);		
					}
				}
			}else{
				$pay_price=$origin_price;
			}
			$order_sn = order_create_no();
			//打印支付日志
			$result = $this->record_log($_POST['user_id'],$_POST['agent_id'],$_POST['store_id'],$_POST['clerk_id'],
						$pay_price,2,$order_sn,$_POST['pay_type'],1,'扫码付款',0,$origin_price,$agent_info['oem_id'],2,
						$agent_info['salesman_id'],$agent_info['agency_id1'],$agent_info['agency_id2'],0,$np_price);
			if($result){
				//发起支付
				if($_POST['pay_type']==3){//支付宝
					if($agent_info['is_state'] == 1){
						$url=pay_code($agent_info['cb_no'],$agent_info['cb_miyao'],$agent_info['cb_clerk'],$pay_price,1,$order_sn,'');
					}else{
						echo '支付失败';exit;
					}
				}elseif($_POST['pay_type']==2) {//微信扫码
					
					if($agent_info['is_state'] == 1){
						$url=pay_code($agent_info['cb_no'],$agent_info['cb_miyao'],$agent_info['cb_clerk'],$pay_price,2,$order_sn,'');
					}else{
						echo '支付失败';exit;
					}
				}
				return json(["code"=>200,"url"=>$url]);
			}
    	}
    }

     //计算付款金额
    function check_money1(){
    	if(request()->isPost()){
			$origin_price = $_POST['origin_price'];	//应付金额
			$pay_price = $origin_price;				//实付金额	
			$agent_info = db('info_agent')->where('id',$_POST['agent_id'])->find();
			$user_info  = db('info_user')->where('id',$_POST['user_id'])->find();		
			$order_sn = order_create_no();
			//打印支付日志
			$result = $this->record_log($_POST['user_id'],$_POST['agent_id'],$_POST['store_id'],$_POST['clerk_id'],
						$pay_price,2,$order_sn,$_POST['pay_type'],1,'扫码付款',0,$origin_price,$agent_info['oem_id'],2,
						$agent_info['salesman_id'],$agent_info['agency_id1'],$agent_info['agency_id2'],3,0);
			if($result){
				//发起支付
				if($_POST['pay_type']==3){//支付宝
					if($agent_info['is_state'] == 1){
						$url=pay_code($agent_info['cb_no'],$agent_info['cb_miyao'],$agent_info['cb_clerk'],$pay_price,1,$order_sn,'');
					}else{
						echo '支付失败';exit;
					}
				}elseif($_POST['pay_type']==2) {//微信扫码
					
					if($agent_info['is_state'] == 1){
						$url=pay_code($agent_info['cb_no'],$agent_info['cb_miyao'],$agent_info['cb_clerk'],$pay_price,2,$order_sn,'');
					}else{
						echo '支付失败';exit;
					}
				}
				return json(["code"=>200,"url"=>$url]);
			}
    	}
    }
    //二维码付款
    function qrcode_pay(){
    	$type=get_brower_type();//判断是微信还是支付宝打开
    	$agent_id=input("agent_id");
		$clerk_id=input("clerk_id")?input("clerk_id"):0;
        $qr_code_number=input("qr_code_number"); 
		if($qr_code_number){
			$agent_qr_code=db('agent_qr_code')->where('qr_code_number',$qr_code_number)->value('agent_id');
			$agent_id=$agent_qr_code;
			if(!$agent_id){
			echo "抱歉该码还未绑定商家!";
			exit;
			}
		}
		if(!$agent_id&&$clerk_id){
			$clerk=db('agent_clerk')->where("id",$clerk_id)->field('agent_id')->find();
			$agent_id=$clerk['agent_id'];
		}
		$redirect='https://'.$_SERVER['HTTP_HOST'].'/index/pay/qrcode_pay?agent_id='.$agent_id.'&store_id='.input('store_id').'&clerk_id='.$clerk_id;
    	if($type==1){
    		$pay_type = 3;
			$field="alipay_id";
			$auth_code=input("auth_code");
			$url ='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.config('alipay_appid').'&scope=auth_base&redirect_uri='.urlencode($redirect);
		}else{
			$pay_type = 2;
			$field="openid";
			$auth_code=input("code");
			$url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect';
		}		
		if(!$auth_code){
			Header("Location: $url");
			exit;
		}else{
			$openid= session('openid');	
			if(!$openid){
				if($type==1){//支付宝openid
				$openid=user_ali_id($auth_code);
				}elseif($type==2){//微信openid
					if(session('cut_auth_code') != $auth_code){
						session('cut_auth_code',$auth_code);
						$openid=user_wx_id($auth_code);
					}else{
						Header("Location: $url");
						exit;
					}
				}
				session('openid',$openid);
			}
			$agent_info = db('info_agent')->where('id',$agent_id)->find();	
			if(!$agent_info){
	    		echo "访问异常，商家不存在";exit;	
	    	}
			if($openid){
				$user=db('info_user')->where($field,$openid)->find();
				
				if(!$user){
					//获取收银员信息
					$clerk_info =  db('agent_clerk')->where('id',input('clerk_id'))->find();
					if($clerk_info){
						$data['level']			= $clerk_info['user_id'];
					}else{
						$data['level']			= $agent_info['user_id'];
					}
					$data[$field]=$openid;
					$data['oem_id']			= $agent_info['oem_id'];
					$data['agency_id']		= $agent_info['agency_id'];
					$data['agency_id1']		= $agent_info['agency_id1'];
					$data['agency_id2']		= $agent_info['agency_id2'];
					$data['salesman_id']	= $agent_info['salesman_id'];
					$data['tj_agent']		= $agent_info['id'];
					$data['add_time']		= now_time();
					$data['reg_type']		= 2;  //扫码付款
					$data['member_level']	= "ratio_one";
					$user_id=Db::name('info_user')->insertGetId($data);
				}else{
					$user_id=$user['id'];
				}
			}
		}
    	$pay_info['user_id']	=	$user_id;
    	$pay_info['agent_id']	=	$agent_info['id'];
    	$pay_info['store_id']	=	input('store_id');
    	$pay_info['clerk_id']	=	input('clerk_id');
		$pay_info['pay_type']	=	$pay_type;
		$cut_user_info = db('info_user')->where('id',$user_id)->find();
		session('info_user',$cut_user_info);
		if($type==2){
			receive();
		}
		$user_info = db('info_user')->where('id',$user_id)->find();
		$where_score['u_id']=$user_id;
		$where_score['order_type']=5;
		$balance = db('log_user_score')->where($where_score)->sum('balance');
		$balance = -$balance;
		$this->assign('balance',$balance);
    	$this->assign('pay_info',$pay_info);
    	$this->assign('agent_info',$agent_info);
		$this->assign('clerk_id',$clerk_id);
		$this->assign('score',$user_info['score']);
    	if($type==1){
    		return  $this->fetch("qrcode_pay1");
    	}else{
    		return  $this->fetch();
    	}
    	
	}
	

	//临时二维码接口
    function ls_qrcode_pay(){
    	$type=get_brower_type();//判断是微信还是支付宝打开
    	$agent_id=input("agent_id");
		$clerk_id=input("clerk_id")?input("clerk_id"):0;
      
		if(!$agent_id&&$clerk_id){
			$clerk=db('agent_clerk')->where("id",$clerk_id)->field('agent_id')->find();
			$agent_id=$clerk['agent_id'];
		}
		$redirect='https://'.$_SERVER['HTTP_HOST'].'/index/pay/ls_qrcode_pay?agent_id='.$agent_id.'&store_id='.input('store_id').'&clerk_id='.$clerk_id;
    	if($type==1){
    		$pay_type = 3;
			$field="alipay_id";
			$auth_code=input("auth_code");
			$url ='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.config('alipay_appid').'&scope=auth_base&redirect_uri='.urlencode($redirect);
		}else{
			$pay_type = 2;
			$field="openid";
			$auth_code=input("code");
			$url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect';
		}		
		if(!$auth_code){
			Header("Location: $url");
			exit;
		}else{
			$openid= session('openid');	
			if(!$openid){
				if($type==1){//支付宝openid
				$openid=user_ali_id($auth_code);
				}elseif($type==2){//微信openid
					if(session('cut_auth_code') != $auth_code){
						session('cut_auth_code',$auth_code);
						$openid=user_wx_id($auth_code);
					}else{
						Header("Location: $url");
						exit;
					}
				}
				session('openid',$openid);
			}
			$agent_info = db('info_agent')->where('id',$agent_id)->find();	
			if(!$agent_info){
	    		echo "访问异常，商家不存在";exit;	
	    	}
			if($openid){
				$user=db('info_user')->where($field,$openid)->find();
				
				if(!$user){
					//获取收银员信息
					$clerk_info =  db('agent_clerk')->where('id',input('clerk_id'))->find();
					if($clerk_info){
						$data['level']			= $clerk_info['user_id'];
					}else{
						$data['level']			= $agent_info['user_id'];
					}
					$data[$field]=$openid;
					$data['oem_id']			= $agent_info['oem_id'];
					$data['agency_id']		= $agent_info['agency_id'];
					$data['agency_id1']		= $agent_info['agency_id1'];
					$data['agency_id2']		= $agent_info['agency_id2'];
					$data['salesman_id']	= $agent_info['salesman_id'];
					$data['tj_agent']		= $agent_info['id'];
					$data['add_time']		= now_time();
					$data['reg_type']		= 2;  //扫码付款
					$data['member_level']	= "ratio_one";
					$user_id=Db::name('info_user')->insertGetId($data);
				}else{
					$user_id=$user['id'];
				}
			}
		}
    	$pay_info['user_id']	=	$user_id;
    	$pay_info['agent_id']	=	$agent_info['id'];
    	$pay_info['store_id']	=	input('store_id');
    	$pay_info['clerk_id']	=	input('clerk_id');
		$pay_info['pay_type']	=	$pay_type;
		$cut_user_info = db('info_user')->where('id',$user_id)->find();
		session('info_user',$cut_user_info);
		if($type==2){
			receive();
		}
		$user_info = db('info_user')->where('id',$user_id)->find();
		$where_score['u_id']=$user_id;
		$where_score['order_type']=5;
		$balance = db('log_user_score')->where($where_score)->sum('balance');
		$balance = -$balance;
		$this->assign('balance',$balance);
    	$this->assign('pay_info',$pay_info);
    	$this->assign('agent_info',$agent_info);
		$this->assign('clerk_id',$clerk_id);
		$this->assign('score',$user_info['score']);
    	if($type==1){
    		return  $this->fetch("ls_qrcode_pay");
    	}else{
    		return  $this->fetch();
    	}
    	
	}
	
        //二维码付款
            //二维码付款
    function qrcode_pay1(){
    	$type=get_brower_type();//判断是微信还是支付宝打开
    	$redirect='https://'.$_SERVER['HTTP_HOST'].'/index/pay/qrcode_pay1?agent_id='.input('agent_id').'&store_id='.input('store_id').'&clerk_id='.input('clerk_id');
    	if($type==1){
    		$pay_type = 3;
			$field="alipay_id";
			$auth_code=input("auth_code");
			$url ='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.config('alipay_appid').'&scope=auth_base&redirect_uri='.urlencode($redirect);
		}else{
			$pay_type = 2;
			$field="openid";
			$auth_code=input("code");
			$url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect';
		}
		if(!$auth_code){
			Header("Location: $url");
			exit;
		}else{
			$openid= session('openid');
			if(!$openid){
				if($type==1){//支付宝openid
					$openid=user_ali_id($auth_code);
				}elseif($type==2){//微信openid
					if(session('cut_auth_code') != $auth_code){
						session('cut_auth_code',$auth_code);
						$openid=user_wx_id($auth_code);
					}else{
						Header("Location: $url");
						exit;
					}
				}
			}
			$agent_info = db('info_agent')->where('id',input('agent_id'))->find();	
			if(!$agent_info){
	    		echo "访问异常，商家不存在";exit;	
	    	}
			if($openid){
				$user=db('info_user')->where($field,$openid)->find();
				if(!$user){
					//获取收银员信息
					$clerk_info =  db('agent_clerk')->where('id',input('clerk_id'))->find();
					if($clerk_info){
						$data['level']			= $clerk_info['user_id'];
					}else{
						$data['level']			= $agent_info['user_id'];
					}
					$data[$field]=$openid;
					$data['oem_id']			= $agent_info['oem_id'];
					$data['agency_id']		= $agent_info['agency_id'];
					$data['agency_id1']		= $agent_info['agency_id1'];
					$data['agency_id2']		= $agent_info['agency_id2'];
					$data['salesman_id']	= $agent_info['salesman_id'];
					$data['tj_agent']		= $agent_info['id'];
					$data['add_time']		= now_time();
					$data['reg_type']		= 5; //二维码付款
					$data['member_level']	= "ratio_one";
					$user_id=Db::name('info_user')->insertGetId($data);
				}else{
					$user_id=$user['id'];
				}
			}
		}
    	$pay_info['user_id']	=	$user_id;
    	$pay_info['agent_id']	=	$agent_info['id'];
    	$pay_info['store_id']	=	input('store_id');
    	$pay_info['clerk_id']	=	input('clerk_id');
    	$pay_info['pay_type']	=	$pay_type;
    	
    	
    	$cut_user_info = db('info_user')->where('id',$user_id)->find();
		session('info_user',$cut_user_info);
		if($type==2){
			receive();
		}
    	$this->assign('pay_info',$pay_info);
    	$this->assign('agent_info',$agent_info);
    	
    	return  $this->fetch();
    }
    public function qrcode_pay2()
    {
    /**
	 * 获取支付宝支付二维码支付
	 */
	 require_once '/extend/dpay/f2fpay/model/builder/AlipayTradePrecreateContentBuilder.php';
	 require_once '/extend/dpay/f2fpay/service/AlipayTradeService.php';
//		import('dpay.f2fpay.model.builder.AlipayTradePrecreateContentBuilder');
//		import('dpay.f2fpay.service.AlipayTradeService');
		$qrPayRequestBuilder = new \AlipayTradePrecreateContentBuilder();
		$qrPay = new \AlipayTradeService($config);
		$providerId = "2088021044805134"; //系统商pid,作为系统商返佣数据提取的依据
		$extendParams = new \ExtendParams();
		$extendParams->setSysServiceProviderId($providerId);
		$extendParamsArr = $extendParams->getExtendParams();
		
		// 支付超时，线下扫码交易定义为5分钟
		$timeExpress = "5m";
		// 创建请求builder，设置请求参数
			//第三方应用授权令牌,商户授权系统商开发模式下使用
		$sell_id="2088102242613573";
		$appAuthToken = "201709BB522f469ee5a9406091fad8f66ccf3X57";//根据真实值填写
		$qrPayRequestBuilder->setSellerId($sell_id);
		$qrPayRequestBuilder->setAppAuthToken($appAuthToken);
		$qrPayRequestBuilder->setOutTradeNo("243533");
		$qrPayRequestBuilder->setTotalAmount(0.01);
		$qrPayRequestBuilder->setTimeExpress($timeExpress);
		$qrPayRequestBuilder->setSubject('消费');
		$qrPayRequestBuilder->setBody("消费");
		//$qrPayRequestBuilder->setUndiscountableAmount($undiscountableAmount);
		//$qrPayRequestBuilder->setExtendParams($extendParamsArr);
		// 调用qrPay方法获取当面付应答
		$qrPayResult = $qrPay->qrPay($qrPayRequestBuilder);
			//	根据状态值进行业务处理
			switch ($qrPayResult->getTradeStatus()){
				case "SUCCESS":
					$response = $qrPayResult->getResponse();
					$qrcode= 'http://www.vshop88.net/code/code.php?url='.urlencode($response->qr_code).'&margin=1&size=10';
					$qrcode= 'http://www.vshop88.net/code/code.php?url='.urlencode($response->qr_code).'&margin=1&size=10';
			//$qrcode = $qrPay->create_erweima($response->qr_code);
			echo "<img src=$qrcode />";
					return $qrcode;
					break;
				case "FAILED":
					break;
				case "UNKNOWN":
					if($qrPayResult->getResponse()){
						print_r($qrPayResult->getResponse());
					}
					break;
				default:
					echo "不支持的返回状态，创建订单二维码返回异常!!!";
					break;
			}
       return  $this->fetch();
    }
    
    /**
	 * 判断订单是否已经支付过
	 */
	public function check_order(){
		$where['sn']=input('WIDout_trade_no');
		$where['status']=2;
		$paylog=db("mall_paylog")->where($where)->find();
		if($paylog){
			return $this->toJson(408, '请勿重复支付');
		}
	}
	
	/**
	 * 支付宝手机支付
	 * $params
	 */
	public function alipay($params = '') {
		//$this->check_order();
		import("payment.alipay.AlipayCore");
		import("payment.alipay.AlipayMd5");
		import("payment.alipay.AlipaySubmit");
		
		if(input('order_type') == 4 || input('order_type') == 5){
			$this->recharge_log();//购买日志
		}
		// 获取缓存配置
		$payment_config = get_config('payment_config');
		//合作身份者ID，签约账号，以2088开头由16位纯数字组成的字符串，查看地址：https://b.alipay.com/order/pidAndKey.htm
		$alipay_config['partner'] = $payment_config['alipay_partner'];
		//收款支付宝账号，以2088开头由16位纯数字组成的字符串，一般情况下收款账号就是签约账号
		$alipay_config['seller_id'] = $payment_config['alipay_seller_id'];
		// MD5密钥，安全检验码，由数字和字母组成的32位字符串，查看地址：https://b.alipay.com/order/pidAndKey.htm
		$alipay_config['key'] = $payment_config['alipay_key'];
		// 服务器异步通知页面路径  需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
		$alipay_config['notify_url'] = url("pay/alipay_notify", '', '', true);
		$alipay_config['return_url'] = url("pay/alipay_return", '', '', true);
		$alipay_config['sign_type'] = strtoupper('MD5');
		$alipay_config['input_charset'] = strtolower('utf-8');
		//ca证书路径地址，用于curl中ssl校验, 请保证cacert.pem文件在当前文件夹目录中
		$alipay_config['cacert'] = getcwd() . '\extend\alipay\cacert.pem';
		$alipay_config['transport'] = 'http';
		$alipay_config['payment_type'] = "1";
		$alipay_config['service'] = "alipay.wap.create.direct.pay.by.user";

		/**************************请求参数**************************/
		//商户订单号，商户网站订单系统中唯一订单号，必填
		$out_trade_no = $_POST['WIDout_trade_no'];
		//订单名称，必填
		$subject = $_POST['WIDsubject'];
		//付款金额，必填
		//$total_fee = $_POST['WIDtotal_fee'];
		$total_fee = 0.01;
		//收银台页面上，商品展示的超链接，必填
		$show_url = $_POST['WIDshow_url'];
		//商品描述，可空
		$body = $_POST['WIDbody'];
		/************************************************************/
		//构造要请求的参数数组，无需改动
		$parameter = array(
			"service" => $alipay_config['service'],
			"partner" => $alipay_config['partner'],
			"seller_id" => $alipay_config['seller_id'],
			"payment_type" => $alipay_config['payment_type'],
			"notify_url" => $alipay_config['notify_url'],
			"return_url" => $alipay_config['return_url'],
			"_input_charset" => trim(strtolower($alipay_config['input_charset'])),
			"out_trade_no" => $out_trade_no,
			"subject" => $subject,
			"total_fee" => $total_fee,
			"show_url" => $show_url,
			//"app_pay" 		 => "Y", //启用此参数能唤起钱包APP支付宝
			"body" => $body,
		);
		//建立请求
		$alipaySubmit = new \AlipaySubmit($alipay_config);
		$html_text = $alipaySubmit->buildRequestForm($parameter, "get", "确认");
		echo $html_text;
	}
	
	
	
	//支付宝回调model1
	public function alipay_noify() {
		$member_model=new Member();
		import("payment.alipay.AlipayCore");
		import("payment.alipay.AlipayMd5");
		import("payment.alipay.AlipayNotify");
		// 获取缓存配置
		$payment_config = get_config('payment_config');
		$alipay_config['partner'] = $payment_config['alipay_partner'];
		$alipay_config['key'] = $payment_config['alipay_key'];
		$alipay_config['sign_type'] = strtoupper('MD5');
		$alipay_config['cacert'] = getcwd() . '\extend\alipay\cacert.pem';
		$alipay_config['transport'] = 'http';
		//计算得出通知验证结果
		$alipayNotify = new \AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyNotify();
		if ($verify_result) {
			//验证成功
			//请在这里加上商户的业务逻辑程序代
			//获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
			//商户订单号
			$out_trade_no = $_POST['out_trade_no'];
			//支付宝交易号
			$trade_no = $_POST['trade_no'];
			//交易状态
			$trade_status = $_POST['trade_status'];

			if ($_POST['trade_status'] == 'TRADE_FINISHED') {
				//判断该笔订单是否在商户网站中已经做过处理
			} else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
				//判断该笔订单是否在商户网站中已经做过处理
				//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
			}
			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
			$member =$member_model-> dopay($out_trade_no);
			echo "success";
			return $this->toJson(200, '支付成功', $member);
			//请不要修改或删除
		} else {
			//验证失败
			echo "fail";
		}
	}
	
	//支付宝回调model2
	public function alipay_return() {
		import("payment.alipay.AlipayCore");
		import("payment.alipay.AlipayMd5");
		import("payment.alipay.AlipayNotify");
		// 获取缓存配置
		$payment_config = get_config('payment_config');
		$alipay_config['partner'] = $payment_config['alipay_partner'];
		$alipay_config['key'] = $payment_config['alipay_key'];
		$alipay_config['sign_type'] = strtoupper('MD5');
		$alipay_config['cacert'] = getcwd() . '\extend\alipay\cacert.pem';
		$alipay_config['transport'] = 'http';
		$alipayNotify = new \AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyReturn();
		if ($verify_result) {//验证成功
			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			//商户订单号
			$out_trade_no = $_GET['out_trade_no'];
			//支付宝交易号
			$trade_no = $_GET['trade_no'];
			//交易状态
			$trade_status = $_GET['trade_status'];
			if ($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
				//判断该笔订单是否在商户网站中已经做过处理
			} else {
				echo "trade_status=" . $_GET['trade_status'];
			}
			$Paylog = new PaylogBaseController();
			$Paylog->print_log($_GET['out_trade_no']);
		} else {
			//验证失败
			echo "fail";
		}
	}
		/**
	 * Post方法
	 * $body     商品描述
	 * $attach   附加数据，在查询API和支付通知中原样返回，可作为自定义参数使用。
	 * $order_no 订单号
	 * $total_fee 价格
	 */
		public function test() {
			//$this->check_order();
			header('Access-Control-Allow-Origin:*');
			import("payment.wxpay.lib.WxPayApi");
			import("payment.wxpay.JsApiPay");
			//①、获取用户openid
			$tools = new \JsApiPay();
			//$openId = $tools->GetOpenid();
			//②、统一下单
			$input = new \WxPayUnifiedOrder();
			// 商品描述
			$input->SetBody('ccc');
			// 商品补充说明
			$input->SetAttach('cccc');
			// 商户订单号32位以下
			$input->SetOut_trade_no(order_create_no());
			// 价格，单位分
			//$input->SetTotal_fee(input("WIDtotal_fee")*100);
			$input->SetTotal_fee(1);
			$input->SetTime_start(date("YmdHis"));
			$input->SetTime_expire(date("YmdHis", time() + 600));
			// 回调通知处理
			$input->SetNotify_url(config('API_DOMAIN').'index/pay/wechat_notify');
			$input->SetTrade_type("JSAPI");
			//$input->SetOpenid(input("openid"));//("otx0ewIY-HKwa5p0gql3bDfp562A");
			$input->SetOpenid(user_wx_id(''));
			$order = \WxPayApi::unifiedOrder($input);
			$jsApiParameters = $tools->GetJsApiParameters($order);
			echo "jsonpCallback"."(".$jsApiParameters.")";
			exit;
	}
	/**
	 * Post方法
	 * $body     商品描述
	 * $attach   附加数据，在查询API和支付通知中原样返回，可作为自定义参数使用。
	 * $order_no 订单号
	 * $total_fee 价格
	 */
		public function wechat() {
			//$this->check_order();
			header('Access-Control-Allow-Origin:*');
			import("payment.wxpay.lib.WxPayApi");
			import("payment.wxpay.JsApiPay");
			if(input('order_type') == 4 || input('order_type') == 5){
				$this->recharge_log();//购买日志
			}
			//①、获取用户openid
			$tools = new \JsApiPay();
			//$openId = $tools->GetOpenid();
			//②、统一下单
			$input = new \WxPayUnifiedOrder();
			// 商品描述
			$input->SetBody(input("WIDsubject"));
			// 商品补充说明
			$input->SetAttach(input("WIDbody"));
			// 商户订单号32位以下
			$input->SetOut_trade_no(input("WIDout_trade_no"));
			// 价格，单位分
			//$input->SetTotal_fee(input("WIDtotal_fee")*100);
			$input->SetTotal_fee(1);
			$input->SetTime_start(date("YmdHis"));
			$input->SetTime_expire(date("YmdHis", time() + 600));
			// 回调通知处理
			$input->SetNotify_url(config('API_DOMAIN').'index/pay/wechat_notify');
			$input->SetTrade_type("JSAPI");
			//$input->SetOpenid(input("openid"));//("otx0ewIY-HKwa5p0gql3bDfp562A");
			$input->SetOpenid("otx0ewI2QwMAgl4HZ43yfCnmXMqQ");
			$order = \WxPayApi::unifiedOrder($input);
			$jsApiParameters = $tools->GetJsApiParameters($order);
			echo "jsonpCallback"."(".$jsApiParameters.")";
			exit;
	}

	//微信支付回调
	public function wechat_notify() {
		import("payment.wxpay.wechat_callback");
		//获取支付回调结果。
		$notify = new \wechat_callback();
		
		$notify->Handle(false);
		
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
		$data = $notify->FromXml($xml);
		
		//处理回调
		if($data['return_code'] == "SUCCESS"){

			//查找当前支付日志状态
			$cut_paylog_info = db('log_paylog')->where('order_sn',$data['out_trade_no'])->find();
			//判断当前是否支付完成
			if($cut_paylog_info['state'] != 2){
				$Paylog = new PaylogBaseController();
				$Paylog->print_log($data['out_trade_no']);
			}else{
				$rest = $notify->ToXml();
				echo $rest;
			}
		}
	}
	
	//购买日志()
	function recharge_log($user_id,$agent_id,$balance,$order_type,$order_sn,$pay_type,$message,$oem_id){
		$agent_info = db('info_agent')->where('id',input('agent_id'))->find();
		//购买日志
		$credit_data = array(
			'uid'			=> $user_id,
			'agent_id' 		=> $agent_id,
			'balance'		=> $balance,
			'order_type' 	=> $order_type,
			'order_sn' 		=> $order_sn,
			'pay_type' 		=> $pay_type,
			'state' 		=> 1,
			"message"		=> $message,
			"order_id"		=> 0,
			"oem_id"		=> $oem_id,
			'add_time' 		=> now_time(),
		);
		$res= db('log_paylog')->insert($credit_data);
		return $res;
	}
	
	//打印支付日志
	function record_log($user_id,$agent_id,$chain_id,$clerk_id,$balance,
	$order_type,$order_sn,$pay_type,$state,$message,$order_id,$origin_price,
	$oem_id,$sy_type,$salesman_id,$agency_id1,$agency_id2,$payment_type=0,$np_price){
		$data['uid']			=$user_id;
		$data['agent_id']		=$agent_id;
		$data['chain_id']		=$chain_id;
		$data['clerk_id']		=$clerk_id;
		$data['balance']		=$balance;
		$data['order_type']		=$order_type;
		$data['order_sn']		=$order_sn;
		$data['pay_type']		=$pay_type;
		$data['state']			=$state;
		$data['message']		=$message;
		$data['order_id']		=$order_id;
		$data['origin_price']	=$origin_price;
		$data['oem_id']			=$oem_id;
		$data['add_time']		=now_time();
		$data['sy_type']		=$sy_type;
		$data['salesman_id']	=$salesman_id;
		$data['agency_id1']		=$agency_id1;
		$data['agency_id2']		=$agency_id2;
		$data['payment_type']		=$payment_type;
		$data['np_price']		=$np_price;
		$res=db('log_paylog')->insert($data);
		return $res;
		
	}
}
